package com.jrx.anytxn.reporting.job.unionFile.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.UnionFileConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liuyu
 * @Description 文件压缩监听，当Job异常、重跑时删除上次生成的压缩文件和.ok文件
 */
@Service
public class CompressUnionFileListener implements JobExecutionListener {

    @Autowired
    private UnionFileConfig unionFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Override
    public void beforeJob(JobExecution jobExecution) {

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        String toDay = DateUtils.format(org.getToday(), "yyyyMMdd");
        String outFilePath = unionFileConfig.getOutUnionFilePath();
        String tarFile = outFilePath + org.getTenantId() + File.separator + toDay + File.separator + toDay + "_" + ReportingConstant.UNION_DEFAULT_TENANT_ID + ".tar";
        // 压缩文件删除
        File file = new File(tarFile);
        if (file.exists()) {
            file.delete();
        }
        // .ok文件删除
        Path reportingFile = Paths.get(outFilePath + org.getTenantId() + File.separator + toDay + File.separator + toDay + "_" + org.getTenantId() + ".ok");
        File toFile = reportingFile.toFile();
        if (toFile.exists()) {
            toFile.delete();
        }

    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }
}
